$(function() {
	showCondition(true, 0, 0, 1, []);// 加载查询条件
	// 开始查询
	var role = $('#roleName_id').val();
	var deps = $('#deps_id').val();
	paramTabPage[tabId].deps = deps;
	// 初始化科室下拉框
	initDepSelect();
	var totalQuota = [{
				"code" : "TotalCaseCnt",
				"desc" : "出院病例数"
			}, {
				"code" : "InCaseCnt",
				"desc" : "入组病例数"
			}, {
				"code" : "InCaseRatio",
				"desc" : "入组率(%)"
			}, {
				"code" : "Over60CaseCnt",
				"desc" : "大于60天病例数"
			}, {
				"code" : "NotInCaseCnt",
				"desc" : "未入组病例数"
			}, {
				"code" : "DeadCaseCnt",
				"desc" : "死亡病例数"
			}];
	/*总体病例分析*/
	loadCaseAnalysis(totalQuota);
	// 查询按钮点击事件
	$("#" + tabId + " #search_png").click(function() {
		var depCodes = $("#" + tabId + " #depId").val();
		if (depCodes && depCodes.length > 0) {
			paramTabPage[tabId].deps = $("#" + tabId + " #depId").val()
					.join(",");
		} else {
			paramTabPage[tabId].deps = "";
			drgUI.warning('请选择科室');
			return;
		}
		loadCaseAnalysis(totalQuota);
	});

	$('#' + tabId + ' #noGroup_id').on('click', function() {
		var param = drgUI.setAjaxData(tabId);
		param.queryType = 'all';
		var pageId = "notInCaseDetail";
		openTab('/pages/yizheng/fenxi/notincaselist.jsp', '未入组病例明细', pageId,
				pageId, param);
	});

	// 加载病例分析页面数据
	function loadCaseAnalysis(totalQuota) {
		caseInfoTotal(totalQuota);// 出院病例统计表-汇总
		caseRiskLevelTotal();// 各死亡风险组入组病例统计表-汇总
		caseNotInDep();// 未入组科室分布
		caseNotInReason();// 未入组原因
		caseNotInDiagnosis();// 未入组主要诊断分布
	}
	// 查询科室
	function initDepSelect() {
		$.ajax({
			url : contextPath + "/DrgsIndexCal/findAllDepByHospCode.dhc",
			type : "post",
			dataType : "json",
			data : paramTabPage[tabId],
			async : false,
			success : function(result) {
				if (result.success) {
					// 科室
					var data = result.data;
					var dataDep = [];
					dataDep = $.extend(dataDep, data);
					dataDep = array_uniquelize(dataDep, "DEPCODE");
					var depsCode = deps.split(",");
					var optStr = "";
					if (role == "科室" ) {
						$('#' + tabId + ' #depGroup_div_id').css("display",
								"none");
						$('#' + tabId + ' #depGroupId')
								.removeClass("selectpicker");
						for (var j = 0; j < depsCode.length; j++) {
							for (var i = 0; i < dataDep.length; i++) {
								var depCode = dataDep[i].DEPCODE;
								if (depCode == depsCode[j]) {
									optStr = optStr + '<option value="'
											+ dataDep[i].DEPCODE
											+ '" selected="selected" >'
											+ dataDep[i].DEPNAME + '</option>';
								}
							}
						}
						$("#" + tabId + " #depId").append(optStr);
					} else {
						for (var i = 0; i < dataDep.length; i++) {
							var depCode = dataDep[i].DEPCODE;
							optStr = optStr + '<option value="'
									+ dataDep[i].DEPCODE
									+ '" selected="selected" >'
									+ dataDep[i].DEPNAME + '</option>';
						}
						$("#" + tabId + " #depId").append(optStr);
						if(commonLayerConfig[0]=="0" && commonLayerConfig[1]=="1"){
							$('#' + tabId + ' #depGroup_div_id').css("display","none");
							$('#' + tabId + ' #depGroupId').removeClass("selectpicker");
						}else if(commonLayerConfig[0]=="1"){
							$('#' + tabId + ' #depGroup_div_id').css("display","block");
							$('#' + tabId + ' #depGroupId').addClass("selectpicker");
							// 科室组
							$.ajax({
								url : contextPath
										+ "/DrgsIndexCal/getDepGroupByCode.dhc",
								type : "post",
								dataType : "json",
								data : paramTabPage[tabId],
								async : false,
								success : function(result) {
									if (result.success) {
										var dataDepgroup = result.data;
										optStr = "";
										for (var i = 0; i < dataDepgroup.length; i++) {
											optStr = optStr + '<option value="'
													+ dataDepgroup[i].CODE
													+ '" selected="selected" >'
													+ dataDepgroup[i].NAME
													+ '</option>';
										}
										$("#" + tabId + " #depGroupId")
												.append(optStr);
									}

								}
							});

							// 科室级联显示
							$("#" + tabId + ' #depGroupId').on('changed.bs.select',
									function(e) {
										var temp = array_filter(dataDep,
												"DEPGROUPCODE", $(this).val());
										$("#" + tabId + " #depId").empty();
										var optStr = "";
										for (var i = 0; i < temp.length; i++) {
											var depCode = temp[i].DEPCODE;
											optStr = optStr + '<option value="'
													+ temp[i].DEPCODE
													+ '" selected="selected" >'
													+ temp[i].DEPNAME + '</option>';
										}
										// 多选下拉框初始化
										$("#" + tabId + " #depId").append(optStr);
										$("#" + tabId + " .selectpicker")
												.selectpicker('refresh');
									});
						}
						
					}
					// 多选下拉框初始化
					$("#" + tabId + " .selectpicker").selectpicker({
								width : 220,// select框宽度
								actionsBox : true,// 全选和取消全选
								liveSearch : true,// 搜索框
								selectAllText : '全选',// selected="selected",
								deselectAllText : '取消全选',
								noneSelectedText : '请选择',
								countSelectedText : "已选中{0}个",// 选中的大于2个时，提示
								selectedTextFormat : "count > 2"
							});
				}
			}
		});
	}

	// 出院病例统计汇总
	function caseInfoTotal(totalQuota) {
		var str = '';
		for(var i=0; i<totalQuota.length;i++){
			var quotaCode = totalQuota[i].code;
			var quotaDesc = totalQuota[i].desc;
			if(i%3==0){
				str += '<tr>';
			}
			str += '<td><p id="'+quotaCode+'-value">'+getQuotaValue(quotaCode,function(code,value){
				if(code=="InCaseRatio" || value<=0){
					$('#'+tabId+' #'+code+'-value').html(value);
				}else{
					$('#'+tabId+' #'+code+'-value').html('<a href=javascript:caseData(\"'+code+'\")>'+formatNumber(value)+'</a>');
				}
			})+'</p><p>'+quotaDesc+'</p></td>';
			if(i%3==2){
				str += '</tr>';
			}
	}
		$("#" + tabId + " #totalOutCase-table").html(str);
		
	}
	
	function getQuotaValue(quotaCode,callback){
		var param = drgUI.setAjaxData(tabId);
		param.isGetCc=0;
		param.monitorType="hosp";
		param.quotaCode = quotaCode;
		$.post(contextPath + "/DrgsIndexCal/indexCal.dhc",param).done(function(result){
			var data = result.data[0];
			var value = 0;
			if(typeof(data)!="undefined"){
				if(typeof(data.QuotaValue)!="undefined"){
					value = data.QuotaValue;
				}else{
					value = 0;
				}
			}else{
				value = 0;
			}
			callback(quotaCode,value);
		})
	}

	/**
	 * 风险等级列表数据
	 */
	function caseRiskLevelTotal() {
		var param=drgUI.setAjaxData(tabId);
		var dateFrom=param.dateFrom;
		var dateTo=param.dateTo;
		$.post(contextPath + "/CaseAnalysis/loadTotalHspRiskGroupInfo.dhc",param).done(function(result) {
			var data = result.data;
			var str = '';
			str += '<table id="totalRisk-CaseAnalysis" class="display dataTable" cellspacing="0" width="100%" role="grid" aria-describedby="example_info">'
			str += '<thead>';
			str += '	<tr role="row">';
			str += '		<th tabindex="0" aria-controls="example" rowspan="1" colspan="1">指标项</th>';
			str += '		<th tabindex="0" aria-controls="example" rowspan="1" colspan="1">DRGs组数</th>';
			str += '		<th tabindex="0" aria-controls="example" rowspan="1" colspan="1">病例数</th>';
			str += '		<th tabindex="0" aria-controls="example" rowspan="1" colspan="1">死亡病例数</th>';
			str += '		<th tabindex="0" aria-controls="example" rowspan="1" colspan="1">死亡率(%)</th>';
			str += '	</tr>';
			str += '</thead>';
			str += '<tbody></tbody>';
			str += '</table>';
			$("#" + tabId + " #totalRisk").html(str);
			var colunms = [{
						"data" : "ASRISKLEVEL"
					}, {
						"data" : "DRGCNT",
						"render" : function(obj, type, full) {
							var riskLevelCode = '';
							switch (full.ASRISKLEVELCODE) {
								case 0 :
									riskLevelCode = '0';
									break;
								case 1 :
									riskLevelCode = '1';
									break;
								case 2 :
									riskLevelCode = '2';
									break;
								case 3 :
									riskLevelCode = '3';
									break;
								case 4 :
									riskLevelCode = '4';
									break;
								default :
									riskLevelCode = '5';
									break;
							}
							return "<a href='javascript:showDRGsDetailCA(\""
									+ dateFrom + "\",\"" + dateTo + "\",\""
									+ riskLevelCode + "\");'>"
									+ formatNumber(full.DRGCNT) + "</a>"
						}
					}, {
						"data" : "RISKCASECNT",
						"render" : function(obj, type, full) {
							var riskDeadCaseCode = '';
							switch (full.ASRISKLEVELCODE) {
								case 0 :
									riskDeadCaseCode = 'Risk0CaseCnt';
									break;
								case 1 :
									riskDeadCaseCode = 'Risk1CaseCnt';
									break;
								case 2 :
									riskDeadCaseCode = 'Risk2CaseCnt';
									break;
								case 3 :
									riskDeadCaseCode = 'Risk3CaseCnt';
									break;
								case 4 :
									riskDeadCaseCode = 'Risk4CaseCnt';
									break;
								default :
									riskDeadCaseCode = 'Risk5CaseCnt';
									break;
							}
							if (full.RISKCASECNT != 0) {
								return "<a href='javascript:caseData(\""
										+ riskDeadCaseCode + "\")'>"
										+ formatNumber(full.RISKCASECNT)
										+ "</a>";
							}
							return formatNumber(full.RISKCASECNT);
						}
					}, {
						"data" : "RISKDEADCASECNT",
						"render" : function(obj, type, full) {
							var riskDeadCaseCode = '';
							switch (full.ASRISKLEVELCODE) {
								case 0 :
									riskDeadCaseCode = 'Risk0DeadCaseCnt';
									break;
								case 1 :
									riskDeadCaseCode = 'Risk1DeadCaseCnt';
									break;
								case 2 :
									riskDeadCaseCode = 'Risk2DeadCaseCnt';
									break;
								case 3 :
									riskDeadCaseCode = 'Risk3DeadCaseCnt';
									break;
								case 4 :
									riskDeadCaseCode = 'Risk4DeadCaseCnt';
									break;
								default :
									riskDeadCaseCode = 'Risk5DeadCaseCnt';
									break;
							}
							if (full.RISKDEADCASECNT != 0) {
								return "<a href='javascript:caseData(\""
										+ riskDeadCaseCode + "\")'>"
										+ formatNumber(full.RISKDEADCASECNT)
										+ "</a>";
							}
							return formatNumber(full.RISKDEADCASECNT);
						}
					}, {
						"data" : "RISKDEADRATIO",
						"render" : function(obj, type, full) {
							return formatNumber(full.RISKDEADRATIO.toFixed(2));
						}
					}];
			var paramsDataTables = {
				dom : 'Brti',
				info : false,
				lengthChange : false,
				searching : false,
				paging : false,
				ordering : false,
				tableTitle : '各死亡风险组入组病例统计表'
			};
			$("#" + tabId + " #totalRisk-CaseAnalysis").dataTableBasic(colunms,
					data, paramsDataTables);
		});

	}

	// 未入组原因分布
	function caseNotInReason() {
		$.post(contextPath + "/CaseAnalysis/loadNotInReason.dhc",
				paramTabPage[tabId]).done(function(result) {
			var data = result.data;
			var pieData = [];
			var fullPieData = [];
			for (var i = data.length - 1; i >= 0; i--) {
				var paramName = (getDicDesc('NOTIN_REASON',data[i].CODE)=='未定义'?'未知':getDicDesc('NOTIN_REASON',data[i].CODE)) + "("
						+ data[i].VALUE + ")";
				var fullName = (getDicDesc('NOTIN_REASON',data[i].CODE)=='未定义'?'未知':getDicDesc('NOTIN_REASON',data[i].CODE));
				if (paramName.length > 5) {
					paramName = paramName.substring(0, 5) + '...';
				}
				pieData.push({
							name : paramName,
							value : data[i].VALUE,
							notInCode : data[i].CODE,
							fullName : fullName
						});
				fullPieData.push({
							name : fullName + "(" + data[i].VALUE + ")",
							value : data[i].VALUE,
							notInCode : data[i].CODE
						});
			}
			var chartParams = {
				subContainer : $('#' + tabId
						+ ' #notInReasonGroupDistributeChart'),
				fullData : fullPieData,
				clickFunc : caseNotInReasonCnt
			};
			pieChartsNotInGroup($('#' + tabId + ' #notInReasonChart'), pieData,
					'未入组原因', '', chartParams);
			$('#' + tabId + ' #notInReasonChart>div').css('cursor', 'pointer');

		});
	}
	// 未入组原因病例明细
	var caseNotInReasonCnt = function caseNotInReasonCntData(piece) {
		var param = drgUI.setAjaxData(tabId);
		param.type1 = piece.data.notInCode;// 未入组病例类型
		param.queryType = 'reason';
		var pageId = piece.data.notInCode + "caseNotInReasonCnt";
		openTab('/pages/yizheng/fenxi/notincaselist.jsp', piece.name + "|"
						+ '病例明细', pageId, pageId, param);
	}
	var diaDep = '';
	var depObject = [];
	// 未入组科室分布
	function caseNotInDep() {
		$.post(contextPath + "/CaseAnalysis/loadNotInDep.dhc",
				paramTabPage[tabId]).done(function(result) {
			var data = result.data;
			var pieData = [];
			var fullPieData = [];
			for (var o in data) {
				depObject[data[o].depCode] = data[o].depName;
				if (data[o].depCode != "qt") {
					diaDep += "'" + data[o].depCode + "'&";
				}
				var paramName = data[o].depName + '(' + data[o].caseCnt + ')';
				var fullName = data[o].depName;
				if (paramName.length > 5) {
					paramName = paramName.substring(0, 5) + '...';
				}
				pieData.push({
							name : paramName,
							value : data[o].caseCnt,
							notInCode : data[o].depCode,
							notInCode : data[o].depCode,
							fullName : fullName
						});
				fullPieData.push({
							name : data[o].depName + '(' + data[o].caseCnt
									+ ')',
							value : data[o].caseCnt,
							notInCode : data[o].depCode
						});
			}
			var chartParams = {
				subContainer : $('#' + tabId + ' #notInDepGroupDistributeChart'),
				fullData : fullPieData,
				clickFunc : caseNotInDepCnt
			};
			pieChartsNotInGroup($('#' + tabId + ' #notInDepChart'), pieData,
					'未入组科室分布', '', chartParams);
			$('#' + tabId + ' #notInDepChart>div').css('cursor', 'pointer');
		});
	}
	// 未入组科室病例明细
	var caseNotInDepCnt = function caseNotInDepCntData(piece) {
		var depCode;
		var tabName;
		if (piece.data.notInCode == "qt") {
			depCode = diaDep.substring(0, diaDep.length - 1);
			tabName = '其他';
		} else {
			depCode = piece.data.notInCode;
			tabName = depObject[piece.data.notInCode];
		}
		var param = drgUI.setAjaxData(tabId);
		param.pardepCode = depCode;
		param.queryType = 'dep';
		var pageId = piece.data.notInCode + "caseNotInDepCnt";
		openTab('/pages/yizheng/fenxi/notincaselist.jsp', tabName + "|"
						+ '病例明细', pageId, pageId, param);
	}
	var diaFive = "";
	// 未入组主要诊断分布
	function caseNotInDiagnosis() {
		$.post(contextPath + "/CaseAnalysis/loadNotInDiagnosis.dhc",
				paramTabPage[tabId]).done(function(result) {
			var data = result.data;
			var pieData = [];
			var fullPieData = [];
			for (var o in data) {
				if (data[o].icd10Code != "qt") {
					diaFive += "'" + data[o].icd10Code.substring(0, 7) + "'&";
				}
				var paramName = data[o].icd10Diag + '(' + data[o].caseCnt + ')';
				var fullName = data[o].icd10Diag;
				if (paramName.length > 5) {
					paramName = paramName.substring(0, 5) + '...';
				}
				pieData.push({
							name : paramName,
							value : data[o].caseCnt,
							notInCode : data[o].icd10Code,
							fullName : fullName
						});
				fullPieData.push({
							name : data[o].icd10Diag + '(' + data[o].caseCnt
									+ ')',
							value : data[o].caseCnt,
							notInCode : data[o].icd10Code
						});
			}
			var chartParams = {
				subContainer : $('#' + tabId
						+ ' #notInMainDaigGroupDistributeChart'),
				fullData : fullPieData,
				clickFunc : caseNotInDiagnosisCnt
			};
			pieChartsNotInGroup($('#' + tabId + ' #notInDiagnosisChart'),
					pieData, '未入组主要诊断分布', '', chartParams);
			$('#' + tabId + ' #notInDiagnosisChart>div').css('cursor',
					'pointer');
		});
		return diaFive;
	}

	// 未入组主要诊断病例明细
	var caseNotInDiagnosisCnt = function caseNotInDiagnosisCntData(piece) {
		var notInDiagCode;
		var tabName;
		if (piece.data.notInCode == "qt") {
			notInDiagCode = diaFive.substring(0, diaFive.length - 1);
			tabName = '其他';
		} else {
			notInDiagCode = piece.data.notInCode;
			tabName = piece.data.notInCode;
		}
		var param = drgUI.setAjaxData(tabId);
		param.type1 = notInDiagCode;// 诊断章节的icd10 Code
		param.queryType = 'diag';
		var pageId = piece.data.notInCode + "caseNotInDiagnosisCnt";
		openTab('/pages/yizheng/fenxi/notincaselist.jsp', tabName + "|"
						+ '病例明细', pageId, pageId, param);
	}

});
// 病例明细跳转
function caseData(caseType) {
	$("#modalcq .close").click();
	var pageId = caseType + "CaseList";

	var param = jQuery.extend(true, {}, paramTabPage[tabId]);
	param.caseLinkCode = caseType;// 所有病例图标按钮 均获取入组病例数
	var desc;// 页面描述
	if (caseType == "NotInCaseCnt") {
		desc = "未入组病例";
	}
	if (caseType == "Over60CaseCnt") {
		desc = "大于60天病例";
	}

	if (caseType == "TotalCaseCnt") {
		desc = "出院病例";
	}
	if (caseType == "InCaseCnt") {
		desc = "入组病例";
	}
	if (caseType == "DeadCaseCnt") {
		desc = "死亡病例";
	}
	if (caseType == "Risk0CaseCnt") {
		desc = "零风险组病例";
	}
	if (caseType == "Risk1CaseCnt") {
		desc = "低风险组病例";
	}
	if (caseType == "Risk2CaseCnt") {
		desc = "中低风险组病例";
	}
	if (caseType == "Risk3CaseCnt") {
		desc = "中高风险组病例";
	}
	if (caseType == "Risk4CaseCnt") {
		desc = "高风险组病例";
	}
	if (caseType == "Risk5CaseCnt") {
		desc = "新增病组病例";
	}
	if (caseType == "Risk0DeadCaseCnt") {
		desc = "零风险组死亡病例";
	}
	if (caseType == "Risk1DeadCaseCnt") {
		desc = "低风险组死亡病例";
	}
	if (caseType == "Risk2DeadCaseCnt") {
		desc = "中低风险组死亡病例";
	}
	if (caseType == "Risk3DeadCaseCnt") {
		desc = "中高风险组死亡病例";
	}
	if (caseType == "Risk4DeadCaseCnt") {
		desc = "高风险组死亡病例";
	}
	if (caseType == "Risk5DeadCaseCnt") {
		desc = "新增病组死亡病例";
	}

	openTab('/pages/drgscommon/case.jsp', desc + "|" + '病例明细', pageId, pageId,
			param);

}

// 加载病组详情表格
function showDRGsDetailCA(dateFrom, dateTo, riskLevel) {
	$.post(contextPath + '/pages/common/top-dialog.jsp').done(function(data){
		var dialog  = $(data);
		dialog.find(".modal-title").html("病组详情");
		dialog.find(".modal-footer").css("border-top","");
		dialog.modal({
			keyboard: false
		}).on({
			'hidden.bs.modal' : function(){
				$(this).remove();
			},
			'shown.bs.modal' : function(){
				dialog.find("#echartcq4").html("<table id = 'drgDetail' width = '100%'><tbody></tbody></table>");
				var param = drgUI.setAjaxData(tabId);
				param.dateFrom = dateFrom;
				param.dateTo = dateTo;
				param.type1 = riskLevel;
				$.post(contextPath + "/CaseAnalysis/drgsDetail.dhc", param).done(function(result) {
					var data = result.data ;
					var columns=[
				                  	{"data": "DRGNAME","title":'DRG描述'},
				                  	{"data": "WEIGHT","title":'权重'},
				                  	{"data": "AVGFEE","title":'次均费用(元)',
				                  		"render": function(obj, type, full) {
				                  			return formatNumber(full["AVGFEE"],2) ;
					                     }
				                  	},
				                  	{"data": "AVGDAY","title":'平均住院日',
				                  		"render": function(obj, type, full) {
				                  			return formatNumber(full["AVGDAY"],2) ;
					                     }
				                  	},
				                  	{"data": "RISKLEVEL","title":'风险等级'}
				                 ];
					var paramsDataTables={searching:true,lengthChange:true,ordering:true,stateSave:false,info:false,scrollX:true,scrollY:'280px',autoWidth:false,orderCellsTop:true,tableTitle:"病组明细"};
					dialog.find("#drgDetail").dataTableBasic(columns,data,paramsDataTables);
				});
			}
		})
	})
	
}
